package com.zd.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.zd.dao.PermissionDao;
import com.zd.dao.RoleDao;
import com.zd.dao.UserDao;
import com.zd.pojo.Permission;
import com.zd.pojo.Role;
import com.zd.pojo.User;
import com.zd.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional//事务注接
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;
    //根据用户名查询数据库获取用户信息和关联的角色信息，同时需要查询角色关联和权限信息
    @Override
    public User findByUsername(String username) {
        User user=userDao.findByUsername((username));//查询用户的基本信息，不包含用户的角色
        if(user==null){
            return null;
        }
        Integer userId = user.getId();
        //根据用户ID查询对应的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        if(roles != null && roles.size() > 0){
            for (Role role : roles) {
                Integer roleId = role.getId();
                //根据角色ID查询关联的权限
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                if(permissions != null && permissions.size() > 0){
                    role.setPermissions(permissions);//让角色关联权限
                }
            }
            user.setRoles(roles);//让用户关联角色
        }
        return user;

    }
}
